﻿CREATE PROCEDURE dbo.SP_MembersInModules_SELECT
@StartIndex INT = NULL,
@lenght INT =  NULL ,
@OrderColume nvarchar(256) = NULL
, @MemberId Int   =  NULL 
, @ModuleId Int   =  NULL 
	AS
			WITH CTE_MembersInModules AS
			( 
			SELECT
 							MemberId,
								ModuleId,
							ROW_NUMBER() OVER (ORDER BY 
        	CASE 
									WHEN @OrderColume='MemberId' THEN MemberId
												WHEN @OrderColume='ModuleId' THEN ModuleId
									ELSE 
							    MemberId
					        	END
			) AS "RowNumber"
  			FROM MembersInModules 
			where 
								(MemberId = @MemberId OR @MemberId Is Null)
										AND(ModuleId = @ModuleId OR @ModuleId Is Null)
								)
			SELECT  *
			FROM CTE_MembersInModules
			WHERE  (RowNumber >= @StartIndex OR @StartIndex Is Null) AND (RowNumber <= @StartIndex+@lenght OR (@StartIndex Is Null and @lenght Is Null))
			Return (select @@ROWCOUNT)
			